package main

import (
	"crypto/md5"
	"encoding/json"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"strings"

	"gitee.com/yanxingshuyuan/backend/server/models"
	"gitee.com/yanxingshuyuan/backend/server/repositories"
	"github.com/jmoiron/sqlx"
	"github.com/spf13/viper"
)

type Config struct {
	DBString string `json:"dbstring"`
	DataDir  string `json:"datadir"`
}

func initConfig() *Config {
	viper.SetConfigType("toml")
	viper.SetConfigName("poems_loader")
	viper.AddConfigPath(".")

	err := viper.ReadInConfig()
	if err != nil {
		log.Fatalf("fatal error: config file %s not found", err)
	}
	config := &Config{}
	config.DBString = viper.GetString("dbstring")
	if config.DBString == "" {
		log.Fatal("Bad Config: No Database String!\n")
		return config
	}
	viper.SetDefault("datadir", "./data/")
	config.DataDir = viper.GetString("datadir")
	return config
}

var tagRepo *repositories.TagRepo
var matRepo *repositories.MatRepo
var peopleRepo *repositories.PeopleRepo

// var allTags mapset.Set

func main() {
	config := initConfig()

	db, err := sqlx.Connect("postgres", config.DBString)
	if err != nil {
		log.Fatal("Error connecting database:\n")
	}

	dir := config.DataDir

	tagRepo = repositories.NewTagRepo(db)
	matRepo = repositories.NewMatRepo(db, dir, tagRepo)
	peopleRepo = repositories.NewPeopleRepo(db)
	loadPoems(dir)
}

func loadPoems(data string) {

	pat := filepath.Join(data, "ci.*.json")
	files, err := filepath.Glob(pat)
	if err != nil {
		fmt.Printf("error globing data files: %#v\n", data)
	}

	if len(files) == 0 {
		fmt.Printf("No files found for %v\n", pat)
	}

	// allTags = mapset.NewSet()

	for n, f := range files {
		fmt.Printf("file:%v,%v\n", n, f)

		loadFile(f)
	}

	/*
		fmt.Printf("%v\n", allTags)

		f, err := os.Create("./tags.txt") //创建文件

		w := bufio.NewWriter(f) //创建新的 Writer 对象
		a := allTags.ToSlice()
		for i := range a {
			w.WriteString(a[i].(string))
			w.WriteString("\n")
		}
		w.Flush()
		f.Close()
	*/

}

type Poem struct {
	Author     string
	Paragraphs []string
	Strains    []string
	Title      string
	Rhythmic   string
	Tags       []string
}

func loadFile(file string) {
	f, err := os.Open(file)
	if err != nil {
		fmt.Printf("Error opening file:%v\n", file)
	}
	defer f.Close()

	var poems []Poem

	decoder := json.NewDecoder(f)
	err = decoder.Decode(&poems)

	if err != nil {
		fmt.Printf("error decoding file: %#v\n", file)
	}

	for _, p := range poems {
		/*
			if len(p.Tags) > 0 {
				// fmt.Printf("%+v\n", p)
					for i := range p.Tags {
						allTags.Add(p.Tags[i])
					}
			}
		*/
		res := poemToResource(p)
		// fmt.Printf("res: %+v", res)

		matRepo.AddResource(&res)
	}
	log.Printf("total counts: %v\n", len(poems))

}

func getPids(author string) string {
	p := peopleRepo.GetOrAddPerson(author, "") // TODO: 从authors.json中导入作者简介
	return p.ID
}

func getTags(vals []string) []models.Tag {
	var tags []models.Tag
	return tags
}

func poemToResource(poem Poem) models.MatForm {
	var res models.MatForm

	res.Content = strings.Join(poem.Paragraphs, "\n")
	res.Title = poem.Title

	res.Kind = models.KindPoem
	res.Pids = getPids(poem.Author)
	res.Tags = getTags(poem.Tags)
	if poem.Title == "" && poem.Rhythmic != "" {
		res.Title = poem.Rhythmic
		rtag := models.Tag{
			Val:  poem.Rhythmic,
			Kind: int(models.KindPoem),
			Cat:  int(models.TagCatTune),
		}
		res.Tags = append(res.Tags, rtag)
	}
	sum := md5.Sum([]byte(res.Content))
	res.Checksum = fmt.Sprintf("%x", sum)
	return res
}
